import 'package:flutter/material.dart';
import 'package:flutter_deer/database/beans/config/res_zero_tube_entity.dart';
import 'package:flutter_deer/database/tables.dart';
import 'package:flutter_deer/res/resources.dart';
import 'package:flutter_deer/ui/cashier/provider/cashier_page_provider.dart';
import 'package:flutter_deer/util/input_formatter/mny_format.dart';
import 'package:flutter_deer/util/user_config_manager.dart';
import 'package:get/get.dart';

/// 合并油单弹窗
class MergeOilOrderDialog extends StatefulWidget {
  const MergeOilOrderDialog({super.key});

  @override
  State<MergeOilOrderDialog> createState() => _MergeOilOrderDialogState();
}

class _MergeOilOrderDialogState extends State<MergeOilOrderDialog> {
  final List<AppOrderBean> _orderList = [];
  late AppZeroModConfig? config;
  final mProvider = Get.find<CashierPageProvider>();

  @override
  void initState() {
    super.initState();
    config = AppZeroModConfig.getConfig();
    _requestOrderList();
  }

  /// 请求可合并的油单列表
  void _requestOrderList() {
    final List<int> nzlList = [];
    if (config?.mergePaymentType == 0) {
      nzlList.add(mProvider.selectListOils.first.nzl);
    } else {
      nzlList.addAll(UserConfigManager.getNzlListByOilId(mProvider.selectListOils.first.mchGoodsId));
    }
    final query = AppOrderBean.queryUnPayOrderMerge(nzlList);
    // query.removeWhere((e) => mProvider.selectListOils.any((element) => element.energyOrderCode == e.energyOrderCode) );
    // query.remove(mProvider.selectListOils);
    mProvider.selectListOils.forEach(query.remove);
    setState(() {
      _orderList.addAll(query);
    });
  }

  /// 选择订单
  void _onSelectOrder(AppOrderBean order) {
    mProvider.selectListOils.add(order);
    Navigator.of(context).pop();
  }

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Dialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
      // insetPadding: EdgeInsets.all(20),
      child: SizedBox(
        width: 550,
        height: screenSize.height * 0.8,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Gaps.vGap15,
            _buildHeader(),
            Gaps.vGap15,
            Expanded(child: _buildOrderList()),
          ],
        ),
      ),
    );
  }

  /// 构建标题栏
  Widget _buildHeader() {
    String str = '';
    if (config?.mergePaymentType == 1) {
      str = '[枪号相同]';
    } else {
      str = '[油品相同]';
    }
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        Row(
            // 垂直方向基于基线对齐
            crossAxisAlignment: CrossAxisAlignment.baseline,
            // 指定使用字母基线
            textBaseline: TextBaseline.alphabetic,
            children: <Widget>[
              const SizedBox(width: 20),
              Text('合并油单', style: TextStyles.textBold24.copyWith(color: Colours.dark_bg_color)),
              const SizedBox(width: 10),
              // Text('共${_orderList.length}笔${str}的油单，可选择进行合并收款', style: TextStyles.textSize16.copyWith(color: Colours.orange)),
              RichText(
                text: TextSpan(
                  children: [
                    TextSpan(
                      text: '共${_orderList.length}笔',
                      style: TextStyles.textSize16.copyWith(color: Colours.orange),
                    ),
                    TextSpan(
                      text: str,
                      style: TextStyles.textSize16.copyWith(color: Colours.green),
                    ),
                    TextSpan(
                      text: '的油单，请选择进行合并收款',
                      style: TextStyles.textSize16.copyWith(color: Colours.orange),
                    ),
                  ],
                ),
              ),
            ]),
        IconButton(
          icon: const Icon(Icons.close),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
      ],
    );
  }

  /// 构建订单列表
  Widget _buildOrderList() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 20),
      child: ListView.builder(
        itemCount: _orderList.length,
        itemBuilder: (context, index) {
          if (index == _orderList.length) {
            return const Padding(
              padding: EdgeInsets.all(8.0),
              child: Center(child: CircularProgressIndicator()),
            );
          }
          final order = _orderList[index];
          return _buildOrderItem(order, index);
        },
      ),
    );
  }

  /// 构建订单项
  Widget _buildOrderItem(AppOrderBean order, int index) {
    final isEven = index % 2 == 0;
    return ColoredBox(
      color: isEven ? const Color(0xFFDBDDE2) : Colors.white,
      child: ListTile(
        contentPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
        title: Row(
          children: <Widget>[
            Expanded(flex: 2, child: Text('${order.mchGoodsName}', textAlign: TextAlign.center)),
            Expanded(flex: 2, child: Text('${order.nzl}号枪', textAlign: TextAlign.center)),
            Expanded(flex: 2, child: Text('${order.vol.toYuan}${order.unitName}', textAlign: TextAlign.center)),
            Expanded(flex: 2, child: Text(order.orderTime, textAlign: TextAlign.center)),
            Expanded(flex: 3, child: Text('￥${order.formatMny}', style: const TextStyle(color: Color(0xFFD76B02)), textAlign: TextAlign.center)),
          ],
        ),
        onTap: () => _onSelectOrder(order),
      ),
    );
  }
}
